<?php

namespace App\Models;

use App\Models\BaseModel;

// use SimpleSoftwareIO\QrCode\Generator;
use Illuminate\Filesystem\Filesystem;

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Response\QrCodeResponse;

class ActivityEnter extends BaseModel
{

    protected $casts = [
        'created_at' => 'Y-m-d H:i:s',
        'updated_at' => 'Y-m-d H:i:s',
        'start_time' => 'Y-m-d H:i:s',
        'end_time' => 'Y-m-d H:i:s',
    ];

    protected $appends = ['created_at', 'updated_at', 'member_name'];

    public function getCreatedAtAttribute()
    {
        if (isset($this->attributes['created_at']))
        {
            return date('Y-m-d H:i:s', strtotime($this->attributes['created_at']));
        }
    }

    public function getUpdatedAtAttribute()
    {
        if (isset($this->attributes['updated_at']))
        {
            return date('Y-m-d H:i:s', strtotime($this->attributes['updated_at']));
        }
    }

    public function getMemberNameAttribute()
    {
        if (isset($this->attributes['member_id']))
        {
            $member = Member::select('name')->where('member_id', $this->attributes['member_id'])->first();
            return isset($member->name) ? $member->name : '';
        }
    }

    //活动报名
    public static function create(array $attributes)
    {
        extract($attributes);

        $member =  \Auth::guard('member')->user();

        $member = Member::where('member_id', $member->member_id)->first();

        // 获取活动信息
        $activity = Activity::where('id', $activity_id)->where('shelves', 1)->first();

        if (!$activity)
        {
            return self::formatError(404 , '活动不存在或未启用');
        }

        // if (time() < strtotime($activity->start_time))
        // {
        //     return self::formatError(400 , '该活动尚未开始，请稍后报名');
        // }

        if (time() >=  strtotime($activity->end_time))
        {
            return self::formatError(400 , '该活动已经结束，请报名其它活动');
        }

        if ($activity->limit_num>0)
        {
            $join_num = self::where('activity_id', $activity->id)->whereIn('status', ['order','finish'])->count();
            if ($join_num >= $activity->limit_num)
            {
                return self::formatError(400 , '该活动报名名额已满，请参与其他活动');
            }
        }

        if ($activity->check_mobile==1 && !$member->mobile)
        {
            return self::formatError(401 , '请在资料里完善手机号');
        }

        // 获取报名信息
        $where = ['member_id' => $member->member_id, 'activity_id' => $activity_id];
        $activity_enter = ActivityEnter::where($where)->first();

        if ($activity_enter && $activity_enter->status=='order')
        {
            return self::formatError(400 , '您已报名该活动，请勿重复报名');
        }

        if ($activity_enter && $activity_enter->status=='finsh')
        {
            return self::formatError(400 , '您已参与过此活动，无法再次参与');
        }

        \DB::beginTransaction();

        // 此处应该走事务
        try {

            // 参与活动
            $activityenter = ActivityEnter::where('activity_id', $activity_id)->where('member_id', $member->member_id)->first();
            if (!$activityenter)
            {
                $activityenter = new ActivityEnter;
            }
            $activityenter->member_id = $member->member_id;
            $activityenter->activity_id = $activity_id;
            $activityenter->title = $activity->title;
            $activityenter->score = $activity->score;
            $activityenter->start_time = $activity->start_time;
            $activityenter->end_time = $activity->end_time;
            $activityenter->imgurl = $activity->imgurl;
            $activityenter->status = 'order';
            $activityenter->exchange_code =self::getExchangeCode();
            $activityenter->apply = $activity->apply;
            $activityenter->mobile = isset($member->mobile) ? $member->mobile : '' ;

            if ($activityenter->exchange_code)
            {
                // $qrcode = new Generator;
                $store_path = storage_path('app/public/activity/');
                $file = new Filesystem();
                if (!$file->exists($store_path) )
                {
                    $file->makeDirectory($store_path, 0777, true, true);
                }
                $name = $activityenter->exchange_code. '.png';
                $code = 'ACTIVITYENTER|||'.$activityenter->exchange_code;
                // $qrcode = $qrcode->format('png')->size(399)->color(40,40,40)->generate($code, $store_path . $name);
                $qrCode = new QrCode($code);
                $qrCode->setSize(300);
                $qrCode->setWriterByName('png');
                $qrCode->setEncoding('UTF-8');
                $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH());
                $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
                $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
                $qrCode->setLogoPath(storage_path('app/public/').$activity->imgurl);
                $qrCode->setLogoSize(80, 80);
                $qrCode->setValidateResult(false);

                $qrCode->setRoundBlockSize(false);
                $qrCode->setMargin(10);
                // $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);
                $qrCode->writeFile($store_path.'/'.$name);

                $qrcode_url = 'activity/' . $name;

                $activityenter->exchange_qrcode = $qrcode_url;
            }

            $activityenter->save();

            \DB::commit();

        } catch (\Exception $exception) {

            \DB::rollback();

            return self::formatError(400 , '参与活动失败:'.$exception->getMessage());
        }

        return self::formatBody(['activityenter' => $activityenter], '活动报名成功');

    }

    // 取消活动参与
    public static function cancel(array $attributes)
    {
        extract($attributes);

        $member =  \Auth::guard('member')->user();

        // 获取活动信息
        $activity = Activity::where('id', $activity_id)->first();

        if (!$activity)
        {
            return self::formatError(404 , '活动不存在');
        }

        if ($activity->apply==0)
        {
            return self::formatError(400 , '此活动无需报名');
        }

        // 获取报名信息
        $where = ['member_id' => $member->member_id, 'activity_id' => $activity_id];
        $activity_enter = ActivityEnter::where($where)->first();

        if (!$activity_enter)
        {
            return self::formatError(400 , '您尚未报名该活动');
        }

        if (!$activity_enter->status=='cancel')
        {
            return self::formatError(400 , '您已取消报名，请勿重复操作');
        }

        if (!$activity_enter->status=='finish')
        {
            return self::formatError(400 , '您已签到完成，无法取消报名');
        }

        // 执行报名取消操作
        $activity_enter->status = 'cancel';
        $activity_enter->save();

        return self::formatBody([], '活动报名取消成功');
    }

    //我参与的活动列表
    public static function getList(array $attributes)
    {
        extract($attributes);

        $member =  \Auth::guard('member')->user();

        $where = ['member_id' => $member->member_id, 'status'=>$status];

        $model = ActivityEnter::where($where);

        $total = $model->count();

        $model->orderBy('updated_at', 'DESC');

        if (isset($per_page))
        {
            $data = $model->paginate($per_page)->toArray();
            foreach ($data['data'] as $k=>$v){
                $data['data'][$k]['member_name'] =$member->name;
                $data['data'][$k]['start_time'] = date("Y-m-d H:i:s",strtotime($v['start_time']));
                $data['data'][$k]['end_time'] = date("Y-m-d H:i:s",strtotime($v['end_time']));
                $data['data'][$k]['created_at'] = date("Y-m-d H:i:s",strtotime($v['created_at']));
                $data['data'][$k]['updated_at'] = date("Y-m-d H:i:s",strtotime($v['updated_at']));
            }

            return self::formatBody(['list' => $data['data'], 'paged' => self::formatPaged($page, $per_page, $total)]);
        }
        else
        {
            $data = $model->get()->toArray();

            return self::formatBody(['list' => $data]);
        }
    }

    //活动签到
    public static function toSignin(array $attributes)
    {
        extract($attributes);

        //管理员会员信息
        $user =  \Auth::guard('member')->user();

        $member_bind = MemberBindAdmin::where('member_id', $user->member_id)->first();

        $where = ['exchange_code' => $exchange_code];

        $model = ActivityEnter::where($where)->first();

        // 用户会员信息
        $member = Member::where('member_id', $model->member_id)->first();

        if (!$user)
        {
            return self::formatError(404 , '未查询到用户信息');
        }

        if (!$model)
        {
            return self::formatError(404 , '未查询到报名记录');
        }

        if ($model->status == 'finish')
        {
            return self::formatError(400 , '您已签到完成，请勿重复签到');
        }

        $act_model = Activity::where('id', $model->activity_id)->first();

        if (!$act_model)
        {
            return self::formatError(404 , '活动不存在，请联系管理员');
        }

        if (time() < strtotime($act_model->start_time))
        {
            return self::formatError(400 , '活动尚未开始');
        }

        if (time() >= strtotime($act_model->end_time))
        {
            return self::formatError(400 , '活动已结束');
        }

        // 去核销
        $model->status = 'finish';
        $model->source = 'admin';
        $model->op_id = $member_bind->admin_id;
        $model->save();

        // 增加积分
        $current_score = intval($member->score) + intval($model->score);
        Member::where('member_id', $member->member_id)->update([
            'score' => $current_score
        ]);

        // 记录积分增加日志
        MemberScoreLog::create([
            'member_id' => $member->member_id,
            'action' => 'increase',
            'score' => intval($model->score),
            'current_score' => $current_score,
            'remark' => $model->title . '活动 ' . $model->activity_id . " 增加了".$model->score. "积分",
        ]);

        return self::formatBody([], '活动签到成功');
    }

    // 获取核销码
    static function getExchangeCode()
    {
        $exchange_code = self::rand_str(8, 1, 1);

        $count = ActivityEnter::where('exchange_code', $exchange_code)->count();

        if ($count > 0) self::getExchangeCode();

        return $exchange_code;
    }

    public static function getSinginLog(array $attributes)
    {
        extract($attributes);

        $member =  \Auth::guard('member')->user();

        $memberBind = MemberBindAdmin::where('member_id', $member->member_id)->first();

        $where = ['source'=>'admin', 'op_id'=>$memberBind->admin_id, 'status'=>'finish'];

        $model = ActivityEnter::where($where);

        $total = $model->count();

        $model->orderBy('updated_at', 'DESC');

        if (isset($per_page))
        {
            $data = $model->paginate($per_page)->toArray();

            return self::formatBody(['list' => $data['data'], 'paged' => self::formatPaged($page, $per_page, $total)]);
        }
        else
        {
            $data = $model->get()->toArray();

            return self::formatBody(['list' => $data]);
        }
    }


}
